<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Validate;
use excel\ExcelReader;
use excel\ExcelDownload;

class Channeltypes extends Common
{

	//框架
    public function index()
    {
        $count = Db::table('cg_channel_types1')->count();
        $data = Db::table('cg_channel_types1')->order("id desc")->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('maxpage',$maxpage);
        $this->assign('count',$count);
        return $this->fetch('index');
    }
    public function add(){

        $validate = new Validate([
            'title'  => 'require|max:100',
            'brief' => 'require|max:200'
        ]);
        $data = [];
        $data['title'] = $this->request->post('title');
        $data['brief'] = $this->request->post('brief');
        if (!$validate->check($data)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }
        $data['cuser'] = $_SESSION['think']['employee_id'];
        $data['ctime'] = time();
        $data['puser'] = $_SESSION['think']['employee_id'];
        $data['ptime'] = time();
        $bool = Db::table('cg_channel_types1')->insert($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"添加成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"添加失败"
            ]);die;
        }

    }

    public function update(){

        $id = $this->request->post('id');
        $validate = new Validate([
            'title'  => 'require|max:100',
            'brief' => 'require|max:200',
            'id' => 'require|number'
        ]);
        $data = [];
        $data['title'] = $this->request->post('title');
        $data['brief'] = $this->request->post('brief');
        $data['id'] = $id;
        if (!$validate->check($data)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }
        $data['puser'] = $_SESSION['think']['employee_id'];
        $data['ptime'] = time();
        $bool = Db::table('cg_channel_types1')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"修改成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"修改失败"
            ]);die;
        }

    }

    public function delete(){
        $id = $this->request->post('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_channel_types1')->where(array('id'=>$id))->delete();
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    //导出当前列表中所有列的信息
    public function exportExcel()
    {
        $titles = ['类型名称', '创建人', '创建时间', '修改人', '修改时间','描述'];
        $data = Db::name('cg_channel_types1')
            ->field('title,cuser,ctime,puser,ptime,brief')
            ->cache(true, 60)->select();
        foreach ($data as $k => $v) {
            $data[$k]['cuser'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['puser'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '以及渠道类型Excel');
    }

    /**
     * 从Excel导入
     */
    public function import()
    {
        $excel = $this->request->post();
        $contract = 0;
        $elevator = 0;
        $conArr = [];
        $eleArr = [];
        $contractArr = [];
        if (isset($excel['contractXls'])) {
            // 导入维保合同
            $reader = new ExcelReader(ROOT_PATH . 'public' . $excel['contractXls']);
            $map = [
                'contractNo' => '合同编号',
                'project' => '项目名称',
                'usingUnit' => '使用单位',
                'payUnit' => '缴费单位',
                'cooLevel' => '级别',
                'num' => '电梯数量',
                'maintainType' => '维保类型',
                'beginDate' => '有效期起',
                'endDate' => '有效期止',
                'monthMoney' => '月保养费',
                'sumMoney' => '合同总额',
                'maintainUnit' => '维保单位',
                'region' => '区域',
                'salesman' => '业务员',
                'serviceStaff' => '客服人员',
                'auditName' => '审核状态',
                'des' => '备注',
            ];
            $data = $reader->exec($map);
            foreach ($data as $k => $v) {
                $data[$k]['auditName'] = $data[$k]['auditName'] == 1 ? '已审核' : '未审核';
                $data[$k]['entryMan'] = session('userInfo.userName');
            }
            if ($this->getModel()->saveAll($data)) {
                $contract = 1;
            };
        }
        if (isset($excel['liftXls'])) {
            //导入电梯档案
            $ereader = new ExcelReader(ROOT_PATH . 'public' . $excel['liftXls']);
            $emap = [
                'usingState' => '电梯状态',
                'fielBoxNo' => '档案盒编号',
                'project' => '项目名称',
                'buildingNo' => '楼号',
                'liftNo' => '梯号',
                'liftIDNo' => '注册代码',
                'manufactureNo' => '生产工号',
                'productNo' => '出场编号',
                'usingNo' => '使用编号',
                'contractNo' => '合同编号',
                'manageUnit' => '管理单位',
                'usingUnitNo' => '使用单位代码',
                'freepart' => '免费零配件标准',
                'beginDate' => '合同开始时间',
                'endDate' => '合同结束时间',
                'address' => '设备地址',
                'liftType' => '电梯类型',
                'usingRegNo' => '使用登记证',
                'safetyOfficer' => '安全管理员',
                'liftModel' => '电梯型号',
                'floor' => '层',
                'station' => '站',
                'door' => '门',
                'loaded' => '载重',
                'speed' => '速度',
                'maintainType' => '维保类型',
                'maintainUnit' => '维保单位',
                'maintainUnit' => '安装单位',
                'insuranceUnit' => '承包单位',
                'insuranceNo' => '保险单号',
                'insuranceTel' => '理赔电话',
                'insuranceEndDate' => '保险到期',
                'showQrDetail' => '显示明细',
                'des' => '备注信息',
                'region' => '维保区域',
                'stationary' => '驻点',
                'serviceStaff' => '客服人员',
                'needIC' => '安装IC卡',
                'yearCheck' => '下次年检日期',
                'brand' => '品牌',
                'certNo' => '合格证号',
                'regulator' => '监管机构',
                'teamName' => '维保小组'
            ];
            $edata = $ereader->exec($emap);
            $contractArr = ['project', 'manageUnit', 'freepart', 'beginDate', 'endDate', 'maintainUnit', 'region', 'serviceStaff'];
            foreach ($edata as $key => $val) {
                switch ($edata[$key]['usingState']) {
                    case 0:
                        $edata[$key]['usingState'] = "在用";
                        break;
                    case 1:
                        $edata[$key]['usingState'] = "报停";
                        break;
                    case 2:
                        $edata[$key]['usingState'] = "报废";
                        break;
                    case 3:
                        $edata[$key]['usingState'] = "暂停保养";
                        break;
                    case 4:
                        $edata[$key]['usingState'] = "外委保养";
                        break;
                }
                switch ($edata[$key]['showQrDetail']) {
                    case 0:
                        $edata[$key]['showQrDetail'] = "否";
                        break;
                    case 1:
                        $edata[$key]['showQrDetail'] = "是";
                        break;
                }
                foreach ($edata[$key] as $k => $v) {
                    if (in_array($k, $contractArr)) {
                        $conArr[$key][$k] = $edata[$key][$k];
                    } else {
                        $eleArr[$key][$k] = $edata[$key][$k];
                    }
                }
            }
            if ($this->getModel()->saveAll($conArr) && $this->getElevatorModel()->saveAll($eleArr)) {
                $elevator = 1;
            }
        }
        if ($contract == 1 || $elevator == 1) {
            return json([
                'success' => true
            ]);
        }
    }
}
